const Service = require('egg').Service;

class MonitorService extends Service{
	async index (){
		return {
			status: 0,
			data: 33322,
			msg: ''
		}
	}
	/**
	 * 保存到redis
	 * @param {*} data 
	 * @returns 
	 */
	async saveToRedis(data){
		const {ctx} = this;
		// 批量添加错误日志
		// const result = await ctx.model.Error.create(data)
		const total = await this.app.redis.llen('web_report_data')
		if(total > this.app.config.redis_consumption.total_limit_web){
			console.log("redis 存储大小限制，已舍弃数据")
			return ;
		}
		const dataStr = JSON.stringify(data);
		const result = await this.app.redis.lpush("web_report_data", dataStr)
		return result
	}

	/**
	 * 从redis中读出数据并存入mongod
	 */
	async saveWebReportDatasFromRedis(){
		// 获取线程数量
		const thread_num = this.app.config.redis_consumption.thread_web;
		for(var i=0;i<thread_num;i++){
			this.getWebItemDataFromRedis();
		}
	}
	/**
	 * 从redis中读出数据
	 */
	async getWebItemDataFromRedis(){
		// 每次读取一条数据
		let data = await this.app.redis.rpop('web_report_data');
		if(!data) return;
		data = JSON.parse(data)
		this.saveToMongo(data);
	}
	/**
	 * 
	 * @param {*} data 
	 * @returns 
	 */
	async saveToMongo(data){
		const ajaxArr = data.filter(item => item.report_type == 'ajax');
		const errorArr = data.filter(item => item.report_type == 'error');
		const pageArr = data.filter(item => item.report_type == 'page');
		if(ajaxArr.length){
			console.log("【sync】正在同步到ajax",ajaxArr.length)
			await this.app.model.Ajax.create(data) ;
		}
		if(errorArr.length){
			console.log("【sync】正在同步到error",errorArr.length)
			await this.app.model.Error.create(data) ;
		}
		if(pageArr.length){
			console.log("【sync】正在同步到page",pageArr.length)
			await this.app.model.Page.create(data) ;
		}
	}

}

module.exports = MonitorService;